/*
 * Filename: g:\espidf_workspace\idf_S3_T-Watch\main\utils\utils.cc
 * Path: g:\espidf_workspace\idf_S3_T-Watch\main\utils
 * Created Date: Friday, June 20th 2025, 12:21:45 pm
 * Author: sss
 * 
 * Copyright (c) 2025 Your Company
 */
#include "utils.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_log.h"
#include <ctype.h>

static const char* TAG = "Utils";
static const char* STORAGE_NAMESPACE = "storage";

Util_nvs::Util_nvs() {
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        // 如果分区表改变或第一次使用，需要擦除NVS分区
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
}

void Util_nvs::save_string(const char* key, const char* value) {
    nvs_handle handle;
    ESP_ERROR_CHECK(nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &handle));
    ESP_ERROR_CHECK(nvs_set_str(handle, key, value));
    ESP_ERROR_CHECK(nvs_commit(handle));
    nvs_close(handle);
}

const char* Util_nvs::read_string(const char* key) {
    nvs_handle handle;
    ESP_ERROR_CHECK(nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &handle));
    nvs_type_t my_type = NVS_TYPE_U8;
    //检测键是否存在
    if (nvs_find_key(handle, key, &my_type) != ESP_OK)
    {
        ESP_LOGI(TAG, "Key not found");
        /* code */
        nvs_close(handle);
        return NULL;
    }

    size_t len = 0;
    ESP_ERROR_CHECK(nvs_get_str(handle, key, NULL, &len));
    char* buffer = (char*) malloc(len);
    ESP_ERROR_CHECK(nvs_get_str(handle, key, buffer, &len));
    nvs_close(handle);
    return buffer;
}


void to_lower(char *str) {
    for (; *str != '\0'; str++) {
        *str = tolower(*str);  // 转换当前字符为小写[1,3,7](@ref)
    }
}
void to_upper(char *str) {
    for (; *str != '\0'; str++) {
        *str = toupper(*str);  // 转换当前字符为大写[1,3,7](@ref)
    }
}